package com.pine.sunshineelder.common.dto;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import lombok.Data;

@Data
public class QueryResult<T> {
	private int totalRows;
	private int totalPages = -1;
	private int pageSize;
	private int pageNo;
	private List<T> rows;

	public int getTotalPages() {
		if (this.totalPages == -1) {
			this.totalPages = this.totalRows / this.pageSize;
			if (this.totalRows % this.pageSize != 0) {
				this.totalPages++;
			}
		}
		return this.totalPages;
	}

	public <R> QueryResult<R> convert(Function<T, R> convertor) {
		QueryResult<R> result = new QueryResult<R>();
		result.setPageNo(pageNo);
		result.setPageSize(pageSize);
		result.setTotalRows(totalRows);
		if (this.rows != null) {
			List<R> newRows = new ArrayList<R>(this.rows.size());
			for (T t : rows) {
				newRows.add(convertor.apply(t));
			}
			result.setRows(newRows);
		}
		return result;
	}

}